import React, { useState, useImperativeHandle, useEffect, forwardRef, useRef } from 'react';
import { updatePrintDesignFile, updateFileContent } from '@/services/systemUtil/printDesignFile';
import { getDesignFileDetailById } from '@/services/systemUtil/printDesignItem';
import { Modal, Spin, Button, Space } from 'antd';
import { PrinterOutlined } from '@ant-design/icons';
import { hiprint, defaultElementTypeProvider } from '@/index';

// const preview: React.FC =forwardRef (props, ref) => {
const PrintDesingPreView = (props, ref) => {
  const hiprintTemplate = useRef();
  const [visible, handleVisible] = useState<boolean>(false);
  const [waitShowPrinter, handleWaitShowPrintere] = useState<boolean>(false);
  // const [hiprintTemplate, handleHiprintTemplate] = useState<object>();
  const [spinning, handleSpinning] = useState<boolean>(true);
  // 纸张宽 mm
  const [width, handleWidth] = useState<string>('0');
  const [panel, setPanel] = useState({});
  // 模板

  // 数据
  const [printData, handlePrintData] = useState<object>();
  //   关闭
  function hideModal() {
    handleVisible(false);
  }
  function print() {
    handleWaitShowPrintere(true);
    hiprintTemplate?.current.print(
      printData,
      {},
      {
        callback: () => {
          handleWaitShowPrintere(false);
        },
      },
    );
  }
  // function toPdf() {
  //   hiprintTemplate?.toPdf(printData, '打印预览pdf');
  // }
  function show(width = '222') {
    // console.log(panel, '---panel---');
    // handleVisible(true);
    // handleSpinning(true);
    handleWidth(panel.panels[0].width + 12);
    // handleHiprintTemplate(hiprintTemplate);

    // console.log('预览', hiprintTemplate);
    $('#preview_content').html(hiprintTemplate.current.getHtml(props.printData));
    // setTimeout(() => {
    //   console.log('预览', hiprintTemplate);
    //   $('#preview_content').html(hiprintTemplate.current.getHtml(props.printData));
    //   handleSpinning(false);
    // }, 500);
  }

  useEffect(() => {
    (async () => {
      // 相当于新建
      if (props.id !== undefined && props.id !== null) {
        const result = await getDesignFileDetailById(props.id);
        //初始化页面
        const fileContext = {
          panels: [
            {
              index: 0,
              paperType: 'A4',
              height: 297,
              width: 210,
              paperHeader: 43.5,
              paperFooter: 841,
              printElements: [],
              paperNumberLeft: 565,
              paperNumberTop: 819,
            },
          ],
        };
        const _customPrintJson = JSON.parse(result.data.fileContext)
          ? JSON.parse(result.data.fileContext)
          : fileContext;

        setPanel(_customPrintJson);
        const fields = result.data.items;

        console.log(result, '---result---');
        $(document).ready(function () {
          hiprint.init({
            providers: [new defaultElementTypeProvider()],
          });
          $('#hiprintEpContainer').empty();

          // hiprint.PrintElementTypeManager.build('#hiprintEpContainer', provider.value);
          $('#hiprint-printTemplate').empty();
          hiprintTemplate.current = new hiprint.PrintTemplate({
            template: _customPrintJson,
            // settingContainer: '#PrintElementOptionSetting',
            // paginationContainer: '.hiprint-printPagination',
          });
          // hiprintTemplate.current.design('#hiprint-printTemplate');
          // 初始化时判断纸张类型
          // if (panel.panels[0].height && panel.panels[0].width) {
          //   for (const key in paperTypes) {
          //     if (
          //       paperTypes[key].height == panel.panels[0].height &&
          //       paperTypes[key].width == panel.panels[0].width
          //     ) {
          //       setPaper(key, { width: panel.panels[0].width, height: panel.panels[0].height });
          //       break;
          //     } else {
          //       setPaper('other', { width: panel.panels[0].width, height: panel.panels[0].height });
          //     }
          //   }
          // }
          // hiprintTemplate.current.setFields(fields);
          // 获取当前放大比例, 当zoom时传true 才会有
          // handleScaleValue(hiprintTemplate.current.editingPanel.scale || 1);
          handleVisible(props.visible);
          handlePrintData(props.printData);
          handleWidth(_customPrintJson.panels[0].width + 12);
          $('#preview_content').html(hiprintTemplate.current.getHtml(props.printData));
        });

        // console.log('hiprint====>');
      }
    })();
  }, [props.id, props.printData, props.visible]);

  // useImperativeHandle(ref, () => ({
  //   show,
  // }));
  return (
    <div>
      <Modal
        visible={visible}
        maskClosable={false}
        onCancel={hideModal}
        width={width + 'mm'}
        title={
          <Space>
            <div style={{ marginRight: '20px' }}>打印预览</div>
            <Button
              loading={waitShowPrinter}
              type="primary"
              onClick={() => {
                print();
              }}
            >
              <PrinterOutlined />
              打印
            </Button>
            {/* <Button
              type="primary"
              onClick={() => {
                toPdf();
              }}
            >
              <PrinterOutlined />
              pdf
            </Button> */}
          </Space>
        }
        footer={[
          <Button
            key="close"
            onClick={() => {
              hideModal();
            }}
          >
            关闭
          </Button>,
        ]}
      >
        {/* 打印内容区域 */}
        {/* <Spin spinning={spinning} style={{ minHeight: '100px' }}> */}
        <div id="preview_content" />
        {/* </Spin> */}
      </Modal>
    </div>
  );
};

// ChildComp = forwardRef(preview);
export default forwardRef(PrintDesingPreView);
